clear all
set more off
cap log close

do "H:\Lavecchia_7086\to-transfer-jan-2022\RESTAT_Replication_Programs\0_Set_Directories.do"


****************************************************************************
* This do-file uses capital_income_8299 
*	- capital gains, income, dividends and rrsp related variables
* 
* Organizes the data by breaking down into 4 subsamples, around reform years
* 
****************************************************************************


log using "$dir_log\2c_Business_Owners.log", replace


****************************************************************************
****************************************************************************

* Step 1: extract SEISW, LTPI (only from 1988) variables for 1982-2006 from LAD read-only files

forvalues year=1982(1)1987{
use lin__i seiswi`year' using "G:\LAD_All_years\LAD_All_year_V5\Data\STATA\STATA\lad`year'.dta"
sort lin__i
gen year=`year'
foreach var in seiswi {
rename `var'`year' `var'
}
save "$dir_data\Capital income years\business_owners_`year'.dta", replace
}

forvalues year=1988(1)2016{
use lin__i seiswi`year' ltpi_i`year' using "G:\LAD_All_years\LAD_All_year_V5\Data\STATA\STATA\lad`year'.dta"
sort lin__i
gen year=`year'
foreach var in seiswi ltpi_i{
rename `var'`year' `var'
}
save "$dir_data\Capital income years\business_owners_`year'.dta", replace
}


* Step 2: append into one file

clear
use "$dir_data\Capital income years\business_owners_1982.dta", replace
forvalues year=1983/2016{
append using "$dir_data\Capital income years\business_owners_`year'.dta"
compress
}
*
save "$dir_data\business_owners_raw.dta", replace


****************************************************************************
* Step 3: calculate 

use "$dir_data\business_owners_raw.dta"

replace ltpi_i=0 if ltpi_i==0 | ltpi_i==. 
replace ltpi_i=1 if ltpi_i>0 | ltpi_i<0
replace seiswi="0" if seiswi==""

gen se_income_lastyear=0
bysort lin__i (year): replace se_income_lastyear=1 if year[_n-1]==year-1 & lin__i[_n]==lin__i[_n-1] & (seiswi[_n-1]=="1" | ltpi[_n-1]==1)

gen se_income_thisyear=0
bysort lin__i (year): replace se_income_thisyear=1 if seiswi=="1" | ltpi==1

gen se_income_nextyear=0
bysort lin__i (year): replace se_income_nextyear=1 if year[_n+1]==year+1 & lin__i[_n]==lin__i[_n+1] & (seiswi[_n+1]=="1" | ltpi[_n+1]==1) 

/*
gen se_income_last3year=0
bysort lin__i (year): replace se_income_last3year=1 if year[_n-2]== year-2 & (seiswi[_n-2]=="1" | seiswi[_n-1]=="1" | seiswi[_n]=="1" | ltpi[_n-2]==1 | ltpi[_n-1]==1| ltpi[_n]==1) & lin__i[_n]==lin__i[_n-1] & lin__i[_n-2]==lin__i[_n] 
bysort lin__i (year): replace se_income_last3year=1 if year[_n-1]== year-1 & ( seiswi[_n-1]=="1" | seiswi[_n]=="1"  | ltpi[_n-1]==1 | ltpi[_n]==1) & lin__i[_n]==lin__i[_n-1] 
*/

keep lin__i year  se_income_lastyear se_income_thisyear se_income_nextyear 

save "$dir_data\business_owners.dta", replace


